﻿using System.Threading;
using System.Web.Mvc;
using JSM;

namespace MVC4Example.Filters
{
	/// <summary>
	/// Filter to initialize global javascript stuff
	/// </summary>
	public class JavaScriptFilter : ActionFilterAttribute
	{
		/// <summary>
		/// Called before the action result executes.
		/// </summary>
		/// <param name="filterContext">The obj filter context.</param>
		public override void OnResultExecuting(ResultExecutingContext filterContext)
		{
			// filtering on child actions is not necessary
			// and ignore filter for ajax calls
			if (filterContext.IsChildAction || 
				filterContext.HttpContext.Request.ContentType.Contains("application/json"))
				return;

			IJavaScriptModelAware javaScriptModelAware = filterContext.Controller as IJavaScriptModelAware;

			if (javaScriptModelAware == null)
				return;

			#region Global JavaScript variables

			javaScriptModelAware.AddJavaScriptVariables(PageLoadEvent.Init,
												"Config.Language", Thread.CurrentThread.CurrentUICulture.ToString(),
												"Config.SomeConfigValue", 1234
												);

			javaScriptModelAware.AddJavaScriptVariables(PageLoadEvent.Ready,
												"GoogleAnalyticsController.ID", "You could get this from your config"
												);
			#endregion

			#region Global JavaScript functions

			// In our example Config.Init has to be called before all action functions.
			// --> so we insert the function to the queue.
			javaScriptModelAware.InsertJavaScriptFunction("Config.Init", PageLoadEvent.Init);
			javaScriptModelAware.AddJavaScriptFunction("GoogleAnalyticsController.Ready");

			#endregion
		}
	}
}